package com.qiyun.dinghuohui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qiyun.dinghuohui.R;
import com.qiyun.dinghuohui.base.BaseActivity;
import com.qiyun.dinghuohui.common.ClientCookie;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.common.GlideImageLoader;
import com.qiyun.dinghuohui.common.ImageUtils;
import com.qiyun.dinghuohui.utils.CommonUtil;
import com.qiyun.dinghuohui.utils.Inject;
import com.qiyun.dinghuohui.utils.LogDebug;
import com.qiyun.dinghuohui.utils.ServerResponse;
import com.qiyun.dinghuohui.vo.PublicSelectParamBean;
import com.qiyun.dinghuohui.widget.MyKeyboard;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by xlm on 2018\6\5 0005
 */

public class GoodsDetailActivity extends BaseActivity {

    @Inject(R.id.back)
    private RelativeLayout mRelaBack;//返回
    @Inject(R.id.title)
    private TextView mTxtTitle;//标题栏(编号，货号)
    @Inject(R.id.submit_btn)
    private TextView mTxtSubmitBtn;//提交按钮
    @Inject(R.id.banner)
    private Banner banner;

    @Inject(R.id.color_part)
    private TagFlowLayout colorsTable; //颜色标签

    @Inject(R.id.size_data)
    private TagFlowLayout sizeTable; //尺码标签

    @Inject(R.id.amount_count)
    private TagFlowLayout countTable; //合计

    @Inject(R.id.count_edit)
    private LinearLayout editTable; //编辑标签
    @Inject(R.id.order_count)
    private TextView mTxtCount;
    @Inject(R.id.goods_recycle)
    private RecyclerView mGoodsRecycle;//搭配商品
    @Inject(R.id.submit_btn)
    private TextView mTxtSubmit;

    private JSONObject object = null;

    private boolean isShowhand = false;

    private String code;
    private String identifier;

    private String[] colors;//颜色
    private String[] s_new;//尺码


    public static void startActivity(Activity context, JSONObject object) {
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("data", object.toString());
        context.startActivity(intent);
    }

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        if (intent != null) {
            try {
                object = new JSONObject(intent.getStringExtra("data"));
                code = object.optString("code");
                identifier = object.optString("goods_code");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_goods_detail);
    }

    @Override
    protected void initViews() {
        if (!CommonUtil.isEmpty(code)) {
            mTxtTitle.setText(String.valueOf(code + " " + identifier));
        }
        banner.setImages(getImagesPath(code)).isAutoPlay(false).setImageLoader(new GlideImageLoader()).start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (position == 0) {
                    BigPictureActivity.startActivity(getThis(), getImagesPath(code).get(position));
                }
            }
        });
    }

    @Override
    protected void onSetListener() {
        mRelaBack.setOnClickListener(getThis());
        mTxtSubmit.setOnClickListener(getThis());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.submit_btn:
                //提交订单信息
                break;
        }

    }

    /**
     * 提交订单信息
     */
    private void submitOrderData() {


    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setColors();
        for (String color : colors) {
            amount.add(0);
        }
        setSizes();
        setCountEdit();
        setCount();
        setGoodsPairsAdapter();
    }

    //获取搭配的数据
    private List<JSONObject> getPairsData() {
        return CommonDataSets.getPairsByGoodsCode(code);
    }

    private List<JSONObject> getGoodByPair(JSONObject object) {
        List<JSONObject> list = new ArrayList<>();
        String code1 = object.optString("code1");
        String code2 = object.optString("code2");
        String code3 = object.optString("code3");
        String code4 = object.optString("code4");
        String code5 = object.optString("code5");
        String code6 = object.optString("code6");
        String code7 = object.optString("code7");
        String code8 = object.optString("code8");
        JSONObject o;
        if (!CommonUtil.isEmpty(code1)) {
            o = CommonDataSets.getGoodsByCode(code1);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code2)) {
            o = CommonDataSets.getGoodsByCode(code2);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code3)) {
            o = CommonDataSets.getGoodsByCode(code3);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code4)) {
            o = CommonDataSets.getGoodsByCode(code4);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code5)) {
            o = CommonDataSets.getGoodsByCode(code5);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code6)) {
            o = CommonDataSets.getGoodsByCode(code6);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code7)) {
            o = CommonDataSets.getGoodsByCode(code7);
            list.add(o);
        }
        if (!CommonUtil.isEmpty(code8)) {
            o = CommonDataSets.getGoodsByCode(code8);
            list.add(o);
        }
        return list;
    }

    private GoodsPairsAdapter adapter;

    private void setGoodsPairsAdapter() {
        mGoodsRecycle.setLayoutManager(new LinearLayoutManager(getThis(), LinearLayoutManager.VERTICAL, false));
        adapter = new GoodsPairsAdapter(R.layout.item_goods_pair, getPairsData());
        mGoodsRecycle.setAdapter(adapter);
    }

    private class GoodsPairsAdapter extends BaseQuickAdapter<JSONObject, BaseViewHolder> {

        public GoodsPairsAdapter(int layoutResId, @Nullable List<JSONObject> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, JSONObject item) {
            String pair_id = item.optString("pair_id");
            //显示搭配的大图
//            ImageUtils.showImage(getThis(), (ImageView) helper.getView(R.id.item_goods_image),
//                    ClientCookie.getServerUrl() + "/goods/pair/" + pair_id + ".jpg");
            ImageUtils.showImage(getThis(), (ImageView) helper.getView(R.id.item_goods_image),
                    ImageUtils.imagUrl);
            helper.setText(R.id.item_goods_id, String.valueOf(pair_id));

            RecyclerView recyclerView = helper.getView(R.id.item_good_recyle);
            recyclerView.setLayoutManager(new LinearLayoutManager(getThis(), LinearLayoutManager.HORIZONTAL, false));
            List<JSONObject> list = getGoodByPair(item);
            setChildAdapter(list, recyclerView, item);
        }
    }

    private void setChildAdapter(List<JSONObject> list, RecyclerView mGoodsRecycle, final JSONObject item) {
        GoodsChildAdapter goodsChildAdapter = new GoodsChildAdapter(R.layout.item_goods_pair_child, list);
        mGoodsRecycle.setAdapter(goodsChildAdapter);
        goodsChildAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PairDetailActivity.startActivity(getThis(), item);
            }
        });
    }

    private class GoodsChildAdapter extends BaseQuickAdapter<JSONObject, BaseViewHolder> {

        public GoodsChildAdapter(int layoutResId, @Nullable List<JSONObject> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, JSONObject item) {

//            ImageUtils.showImage(getThis(), (ImageView) helper.getView(R.id.item_goods_image),
//                    ClientCookie.getServerUrl() + "/goods/img/" + "1504" + ".jpg");
            ImageUtils.showImage(getThis(), (ImageView) helper.getView(R.id.item_goods_image),
                    ImageUtils.imagUrl);
            helper.setText(R.id.item_goods_id, item.optString("code"));
        }
    }

    //显示合计
    private void setCount() {

        countTable.setAdapter(new TagAdapter<Integer>(amount) {
            @Override
            public View getView(FlowLayout flowLayout, int i, Integer s) {
                TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, countTable, false);
                tv.setText(String.valueOf(amount.get(i)));
                return tv;
            }
        });
    }

    private List<Integer> amount = new ArrayList<>();

    //创建输入框
    private void setCountEdit() {
        final int line = colors.length;
        final int row = s_new.length;
        final List<MyKeyboard> keyList = new ArrayList<>();
        for (int i = 0; i < line; i++) {
            LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setHorizontalGravity(LinearLayout.HORIZONTAL);
            for (int j = 0; j < row; j++) {
                //禁止系统输入法
                final MyKeyboard et = (MyKeyboard) getLayoutInflater().inflate(R.layout.item_goods_edit, linearLayout, false);
                et.setTag(i + "_" + j);
                keyList.add(et);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    et.setShowSoftInputOnFocus(false);
                }

                et.setOnKeyDown(new MyKeyboard.OnKeyDown() {

                    @Override
                    public void OnTouchDown() {
                    }

                    @Override
                    public void OnKeyDownNumber() {
                    }

                    @Override
                    public void OnKeyDownNext() {
                    }

                    @Override
                    public void OnKeyDownEnter() {
                        amount.clear();
                        int index = 1;
                        int allcount = 0;

                        int times = keyList.size() / row;
                        do {
                            List<MyKeyboard> listTemp = null;
                            listTemp = keyList.subList(row * (index - 1), row * index);// listTemp是分段处理逻辑的参数
                            //遍历当前的值是否正确
                            StringBuilder result = new StringBuilder();
                            int num = 0;
                            for (int i = 0; i < listTemp.size(); i++) {
                                String text = listTemp.get(i).getText().toString();
                                if (text.length() == 0) {
                                    text = "0";
                                }
                                num += Integer.parseInt(text);
                                result.append(listTemp.get(i).getText().toString()).append(",");
                            }

                            amount.add(num);
                            allcount += num;
                            LogDebug.d("第" + index + "轮:>>" + result + "------和------" + num);
                            index++;
                        }
                        while (index <= times);
                        setCount();
                        mTxtCount.setText(String.valueOf("合计：" + allcount + "件"));
                        for (MyKeyboard myKeyboard : keyList) {
                            myKeyboard.clearFocus();
                        }
                    }
                });
                linearLayout.addView(et);
            }

            editTable.addView(linearLayout);
        }
    }

    //设置尺码
    private void setSizes() {
        if (object != null && object.length() != 0) {
            String[] sizes = object.optString("size_string").split(",");
            String[] size_new = null;
            if (isShowhand) {
                size_new = new String[sizes.length + 1];
                System.arraycopy(sizes, 0, size_new, 0, sizes.length);
                size_new[sizes.length] = "手数";
            }
            s_new = isShowhand ? size_new : sizes;

            sizeTable.setAdapter(new TagAdapter<String>(s_new) {
                @Override
                public View getView(FlowLayout flowLayout, int i, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, colorsTable, false);
                    tv.setText(s_new[i]);
                    return tv;
                }
            });
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(sizeTable.getLayoutParams());
            lp.width = CommonUtil.dip2px(s_new.length * 55, getThis());
            sizeTable.setLayoutParams(lp);
        }
    }

    //获取颜色标签
    private void setColors() {
        if (object != null && object.length() != 0) {
            colors = object.optString("color_string").split(",");
            final String[] color_new = new String[colors.length + 1];
            for (int i = 0; i < color_new.length; i++) {
                if (i == 0) {
                    color_new[0] = "";
                } else {
                    color_new[i] = colors[i - 1];
                }
            }
            colorsTable.setAdapter(new TagAdapter<String>(color_new) {
                @Override
                public View getView(FlowLayout flowLayout, int i, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_tag_common, colorsTable, false);
                    tv.setText(color_new[i]);
                    return tv;
                }
            });
        }
    }

    //通过code获取搭配数据,搜集搭配里边的code,拼接轮播图
    private List<String> getImagesPath(String code) {
        List<JSONObject> list = CommonDataSets.getPairsByGoodsCode(code);
        Set<String> strings = new HashSet<>();
//        strings.add(ClientCookie.getServerUrl() + "/goods/img/" + "1504" + ".jpg");
        strings.add(ImageUtils.imagUrl);
        for (JSONObject jo : list) {
            for (int i = 1; i < 9; i++) {
                String code1 = jo.optString("code" + i);
                if (!CommonUtil.isEmpty(code1)) {
                    String url = ClientCookie.getServerUrl() + "/goods/img/" + code1 + ".jpg";
//                    String url = ClientCookie.getServerUrl() + "/goods/img/" + "1504" + ".jpg";
                    strings.add(url);
                }
            }
        }
        return new ArrayList<>(strings);
    }

    //接口实现

    @Override
    public void onPostDataStart() {

    }

    @Override
    public void onPostDataSuccess(ServerResponse response) {

    }

    @Override
    public void onPostDataError(ServerResponse response) {

    }

    @Override
    public void onPostDataComplete(ServerResponse response) {

    }

    @Override
    public void setProgressMessage(String message) {

    }

    @Override
    public void publicSelectCallBack(PublicSelectParamBean pspb) {

    }
}
